package com.bawei.es.controller;

import com.bawei.common.core.domain.R;
import com.bawei.es.service.EsIndexService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.common.settings.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author LiZizheng
 */
@RestController
@RequestMapping("/esIndex")
@Api(tags = "ES索引管理")
public class EsIndexController {

    @Autowired
    private EsIndexService esIndexService;

    /**
     * 根据索引名称创建索引
     *
     * @return
     */
    @GetMapping("/create")
    @ApiOperation("根据索引名称创建索引")
    public R<Boolean> indexCreate(String indexName, Settings settings) {
        return esIndexService.indexCreate(indexName,settings);
    }

    /**
     * 根据索引名称、映射结构创建索引
     *
     * @return
     */
    @GetMapping("/createWithMapping")
    @ApiOperation("根据索引名称、映射结构创建索引")
    public R<Boolean> indexCreateWithMapping(String indexName, String indexMapping) {

        return esIndexService.indexCreateWithMapping(indexName,indexMapping);
    }

    /**
     * 根据索引名称查询索引是否存在
     *
     * @return
     */
    @GetMapping("/indexExit")
    @ApiOperation("根据索引名称查询索引是否存在")
    public R<Boolean> indexExit(String indexName) {

        return esIndexService.indexExit(indexName);
    }

    /**
     * 根据索引名称删除索引
     *
     * @return
     */
    @GetMapping("/indexDelete")
    @ApiOperation("根据索引名称删除索引")
    public R<Boolean> indexDelete(String indexName) {
        return esIndexService.indexDelete(indexName);
    }

    /**
     * 根据索引名称获取mapping
     *
     * @return
     */
    @GetMapping("/indexGetMapping")
    @ApiOperation("根据索引名称删除索引")
    public R<Map> indexGetMapping(String indexName) {

        return esIndexService.indexGetMapping(indexName);
    }

    /**
     *根据一个根据索引名称查询详情
     */
    @GetMapping("/{indexName}")
    public R<Map<String, Object>> getIndexDetails(@PathVariable String indexName) {
        try {
            Map<String, Object> indexDetails = esIndexService.getIndexDetails(indexName);
            return R.ok(indexDetails);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("Failed to retrieve index details");
        }
    }

    /**
     * 根据索引名称修改索引
     */
//    @PutMapping("/{indexName}")
//    @ApiOperation("根据索引名称修改索引")
//    public R<Boolean> updateIndex(@PathVariable String indexName, @RequestBody EsParams esParams) {
//        try {
//            boolean result = esIndexService.indexUpdate(indexName, esParams);
//            return R.ok(result);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return R.fail("Failed to update index");
//        }
//    }
}
